import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { FormInstance } from 'antd/lib/form';
import { Modal, Button, message, Input, Select, Form, Upload, Row, Col } from 'antd';
import { getToken } from '@/utils/utils';
import { fromJS } from 'immutable';
import { getOptAuthHeaders } from '@/utils/common';

const mapStateToProps = (state: any) => ({
    account: state.account,
    loading: state.loading.effects['collectionGroupEdit/postObjWithRes'],
});
class ExportModal extends PureComponent<any, any> {

    formRef = React.createRef<FormInstance>();

    constructor(props: any) {
        super(props);
        this.state = {
          vinData: [],
          fileList: [],
          fileUrl: "",
        };
    }
    componentWillMount() {

      }
    componentDidMount() {
      const { dispatch } = this.props;
      dispatch({
        type: 'collectionGroupEdit/getData',
        payload: { url: '/common/template/detail', templateCode: 'dataCollectionImport' },
        callback: (res: any) => {
          this.setState({ fileUrl: res.data ? res.data.templateUrl : null });
        },
      });
    }
    ok = () => {
      const{getImportData}=this.props;
      const {vinData}=this.state;
      getImportData(vinData);
      this.close();
  }


    close = () => {
        const { closeModal } = this.props;
        closeModal();
        this.setState({
          vinData: [],
          fileList: [],
          //fileUrl: "",
        })
    };
    handleChange = (info: any) => {
      const { fileList, file } = info;
      const newList = this.removeList(fileList, file);
      if (
        file.status === 'done' &&
        file.response &&
        file.response.statusCode === '0' &&
        file.response.data
      ) {
        message.success(`${file.name} 上传成功`);
        this.setState({
          vinData: file.response.data
        })
      } else if (file.status === 'done' && file.response && file.response.statusCode !== '0') {
        if(file.response.data){
          message.error(file.response.data +'在'+ file.response.statusMessage);
        }else{
          message.error(file.response.statusMessage);
        }
        this.setState({ fileList: []})
        // this.setState({ fileList: newList });
        return;
      } else if (file.status === 'removed') {
        message.success('删除成功');
        return;
      } else if (file.status === 'error') {
        message.error(`${file.name} 上传失败`);
        this.setState({ fileList: newList });
        return;
      } else if (!file.status) {
        this.setState({ fileList: newList });
        return;
      }
      this.setState({ fileList });
    };
    removeList = (fileList: any, file: any) => {
      const newList = fromJS(fileList).toJS();
      const i = newList.findIndex(e => e.uid === file.uid);
      if (i >= 0) {
        newList.splice(i, 1);
      }
      return newList;
    };
     // 文件上传前校验
  beforeFileUpload = file => {
    const {fileList}=this.state;
    const isXlsx = file.name.endsWith('.xlsx');
    if (!isXlsx) {
      message.error('请上传.xlsx格式文件');
      return false;
    }

    if(fileList.length === 1){
      message.warning('只能上传一个文件！');
      return false;
    }
    return true;
  };
  // 文件删除
  handleRemove = (file: any) => {
    const { fileList } = this.state;
    const newList = this.removeList(fileList, file);
    this.setState({ fileList: newList });
  };
    render() {
      const {fileUrl} =this.state;
      const domain = window.g.url;
      const uploadUrl = '/data/collection/vehicle/import';
      const uploadStr = `${domain}${uploadUrl}`;
      const { modalVisible, loading } = this.props;
        const footer = (
            <div>
                <Button  onClick={this.close}>取消</Button>
                <Button  loading={loading} onClick={this.ok} type="primary">确认</Button>
            </div>
        );
        const props = {
          action: uploadStr,
          headers: { OptAuthorization: `${getToken()}`, ...getOptAuthHeaders() },
          multiple: false,
          accept: '.xls,.xlsx,application/vnd.ms-excel',
          onRemove: this.handleRemove,
          beforeUpload: this.beforeFileUpload,
          onChange: this.handleChange,
        };
        return (
            <Modal
                style={{ top: 20 }}
                footer={footer}
                title="批量导入采集车辆"
                visible={modalVisible}
                onCancel={this.close}
            >
                 <Row>
              <Col span={4}>
              <Upload {...props} fileList={this.state.fileList}>
                        <Button type="primary">
                            导入
                        </Button>
                </Upload>
                </Col>
                <Col span={4}>
                <span >
                {fileUrl === '' ? (
                      <a disabled title="点击下载模板文件">
                        暂无模板下载
                      </a>
                    ) : (
                      <a href={fileUrl} title="点击下载模板文件">
                        模板下载
                      </a>
                    )}
                </span>
                </Col>
             </Row>
            </Modal>
        );
    }
}
export default connect(mapStateToProps)(ExportModal);